//
// Created by 19693 on 2023/11/28.
//
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_log.h"
#include "uart_wave.h"

/**
 * This is an example which echos any data it receives on configured UART back to the sender,
 * with hardware flow control turned off. It does not use UART driver event queue.
 *
 * - Port: configured UART
 * - Receive (Rx) buffer: on
 * - Transmit (Tx) buffer: off
 * - Flow control: off
 * - Event queue: off
 * - Pin assignment: see defines below (See Kconfig)
 */

#define ECHO_TEST_TXD (16)
#define ECHO_TEST_RXD (17)
#define ECHO_TEST_RTS (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS (UART_PIN_NO_CHANGE)

#define ECHO_UART_PORT_NUM      (2)

#define BUF_SIZE (1024)


void uart_config_init() {
    /* Configure parameters of an UART driver,
     * communication pins and install the driver */
    // 调试串口配置
    uart_config_t uart2_config = {
            .baud_rate = 115200,
            .data_bits = UART_DATA_8_BITS,
            .parity    = UART_PARITY_DISABLE,
            .stop_bits = UART_STOP_BITS_1,
            .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
            .source_clk = UART_SCLK_DEFAULT,
    };

    // 超声波配置
    uart_config_t uart1_config = {
            .baud_rate = 9600,
            .data_bits = UART_DATA_8_BITS,
            .parity    = UART_PARITY_DISABLE,
            .stop_bits = UART_STOP_BITS_1,
            .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
            .source_clk = UART_SCLK_DEFAULT,
    };
    int intr_alloc_flags = 0;

    // 超声波驱动安装
    ESP_ERROR_CHECK(uart_driver_install(1, BUF_SIZE * 2, 0, 0, NULL, intr_alloc_flags));
    ESP_ERROR_CHECK(uart_param_config(1, &uart1_config));
    ESP_ERROR_CHECK(uart_set_pin(1, 6, 7, ECHO_TEST_RTS, ECHO_TEST_CTS));

    ESP_ERROR_CHECK(uart_driver_install(ECHO_UART_PORT_NUM, BUF_SIZE * 2, 0, 0, NULL, intr_alloc_flags));
    ESP_ERROR_CHECK(uart_param_config(ECHO_UART_PORT_NUM, &uart2_config));
    ESP_ERROR_CHECK(uart_set_pin(ECHO_UART_PORT_NUM, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));

}

void uart_send_int(int num) {
    char str[50];
    sprintf(str, "%dmm\r\n", num);
    for (int i = 0; i < strlen(str); ++i) {
        uart_write_bytes(ECHO_UART_PORT_NUM, (const uint8_t *) &str[i], 1);
    }
}

void read_distance(int *distance) {
    uint8_t read[1] = {0x55};
    uint8_t *buffer = (uint8_t *) malloc(BUF_SIZE);
    uart_write_bytes(1, (uint8_t *) read, 1);

    int length = 2;
//        ESP_ERROR_CHECK(uart_get_buffered_data_len(1, (size_t*)&length));
    int ret = uart_read_bytes(1, buffer, length, 20 / portTICK_PERIOD_MS);
//        printf("ret :%d\r\n", ret);
    if (ret == 2) {
        *distance = (int) (buffer[0] * 256 + buffer[1]);
//        printf("test: %d\r\n", *distance);
        vTaskDelay(pdMS_TO_TICKS(500));
    }
}